#!/usr/bin/perl

use lib '../rrdtool/lib';

use strict;
use warnings;
use DB;
use Time::HiRes qw/usleep/;
use Data::Dumper;
use threads;

sub run_thread
{
  my ($sql, $msleep) = @_;
  $msleep ||= 100;
  $msleep = int($msleep * 500);

  my $db = DB->new (
    host => 'localhost',
    port => 3306,
    database => 'testing',
    user => 'root',
    pass => 'mysqlpass',
  );

  my $sth = $db->prepare ($sql);
  die "failed to prepare statement ($sql)\n" unless ($sth);

  $sql = substr ($sql, 0, 15);
  my $sleep = int ($msleep * (1 + rand (1)));
  while (1)
  {
    unless ($sth->execute)
    {
      die "failed to run sql ($sql)\n";
    }
    if (time % 60 == 1)
    {
      $sleep = int ($msleep * (1 + rand (1)));
    }
    printf ("%s - %d\n", $sql, $sleep);
    usleep($sleep);
  }

  $db->disconnect;
}

my $select_thread = threads->create ('run_thread', 
  'select * from tbl limit 1', 100);
my $update_thread = threads->create ('run_thread', 
  'update tbl set v = "value" limit 1', 300);
my $insert_thread = threads->create ('run_thread', 
  'insert into tbl (k,v) values ("key", "value") on duplicate key update v = values(v)',
  500);
my $delete_thread = threads->create ('run_thread', 
  'delete from tbl where k = "nokey"', 750);

$select_thread->join;
$update_thread->join;
$insert_thread->join;
$delete_thread->join;
